<template>
  <el-card class="container">
    <el-row type="flex" justify="space-between" class="mb10">
      <el-col>
        <el-button size="small" @click="handleBack">返回上一页</el-button>
        <span style="font-weight: bold; margin-left: 10px">{{ title }}</span>
      </el-col>
      <div>
        <el-button type="primary" size="mini" @click="handleSubmit">提交</el-button>
      </div>
    </el-row>
    <div class="content">
      <el-form :model="form" :rules="rules" ref="form" label-width="160px" size="small">
        <el-card header="配比基本信息" :borderd="false" shadow="never" :body-style="{ padding: 20 }" class="mb10">
          <el-row>
            <el-col :span="12">
              <el-form-item label="配比名称" prop="ratioName">
                <el-input v-model="form.ratioName" placeholder="请输入配比名称" />
              </el-form-item>
              <el-form-item label="搅拌时间" prop="stirringTime">
                <el-input v-model="form.stirringTime" placeholder="请输入搅拌时间" />
              </el-form-item>
              <el-form-item label="盘方量" prop="squareMeasure">
                <el-input v-model="form.squareMeasure" placeholder="请输入盘方量" />
              </el-form-item>
              <el-form-item label="单方容量" prop="unilateralCapacity">
                <el-input v-model="form.unilateralCapacity" placeholder="请输入单方容量" />
              </el-form-item>
              <el-form-item label="水胶比" prop="waterBinderRatio">
                <el-input v-model="form.waterBinderRatio" placeholder="请输入水胶比" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="主标号" prop="primaryDesignatorId">
                <el-select v-model="form.primaryDesignatorId" placeholder="请选择" @change="handlePrimaryIdChange">
                  <el-option style="width: 220px" v-for="(item, index) in PrimaryNameList" :value="item.id" :key="index"
                    :label="item.name"></el-option>
                </el-select>
              </el-form-item>
              <el-form-item label="出机坍稠" prop="outletThickened">
                <el-select v-model="form.outletThickened" placeholder="请选择">
                  <el-option value="80" label="80"></el-option>
                  <el-option value="200" label="200"></el-option>
                </el-select>
              </el-form-item>
              <el-form-item label="出机温度" prop="temperature">
                <el-input v-model="form.temperature" placeholder="请输入出机温度" />
              </el-form-item>
              <el-form-item label="砂率" prop="sandRatio">
                <el-input v-model="form.sandRatio" placeholder="请输入砂率" />
              </el-form-item>
              <el-form-item label="外加剂参量" prop="admixtureParameter">
                <el-input v-model="form.admixtureParameter" placeholder="请输入外加剂参量" />
              </el-form-item>
            </el-col>
          </el-row>
        </el-card>

        <el-card header="原材料信息" :borderd="false" shadow="never" :body-style="{ padding: 20 }" class="mb10">
          <el-table :data="tableData">
            <el-table-column v-for="(item1, index1) in tableColData" :key="index1" align="center" prop=""
              :label="item1.name">
              <el-table-column v-for="(item2, index2) in item1.children" :key="index2" :prop="item2.prop"
                :label="item2.name" align="center" width="100px">
                <template #default="scope">
                  <div v-if="scope.$index === 0">
                    <el-button v-if="scope.row[item2.id]" class="close-button" @click="handlerClick(item2.id, true)"
                      size="small">
                      {{ scope.row[item2.id] }} <i class="el-icon-close"></i>
                    </el-button>
                    <el-button v-else @click="handlerClick(item2.id)" size="small">选择原料</el-button>

                  </div>
                  <div v-else>
                    <el-input v-model="scope.row[item2.id]" placeholder="请输入数字"></el-input>
                  </div>
                </template>
              </el-table-column>
            </el-table-column>
          </el-table>
        </el-card>
        <el-card header="其他信息" class="mt10" v-if="form.id">
          <el-row>
            <el-col :span="12">
              <el-form-item label="配比编号" prop="ratioNo">
                <el-input v-model="form.ratioNo" placeholder="请输入配比编号" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="更新时间" prop="updateTime">
                <el-input v-model="form.updateTime" placeholder="请输入更新时间" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="更新人" prop="createBy">
                <el-input v-model="form.createBy" placeholder="请输入更新人" />
              </el-form-item>
            </el-col>
          </el-row>
        </el-card>
      </el-form>
    </div>
    <custom-dialog :dialog-visible.sync="dialogVisible" @closeHandler="closeHandler" ref="customDialog" />
  </el-card>

</template>

<script>
import { getMaterialCodeList } from "@/api/service/qualityCenter";
import { listDesignator } from "@/api/service/main";
import CustomDialog from "./components/dialog.vue"
import {
  updateOrders,
  getOrders,
  addOrders,
  // addRepair,
  // updateRepair,
} from "@/api/service/arrive/enter.js";
export default {
  components: {
    CustomDialog
  },
  data() {
    return {
      dialogVisible: false,
      contraVisible: false,
      originData: [
        {
          "categoryId": 2, // 码表分类ID:2 name:"水1"
          "categoryName": "水1",
          "materialId": 0,
          "materialName": "",
          "ratioId": 0,
          "value": 111,
        },
      ],
      tableData: [
        {
          '2': "水泥",
        },        
        {
          '2': 111,
          '3': 112,
          '4': 113,
          '5': 114,
          '6': 111,
          '33': 111,
          '30': 111,
          'v8': 111,
          'v9': 111,
          'v10': 111,
          'v11': 111,
          'v12': 111,
          'v13': 111,
          'v14': 115,
          'v15': 116,
          'v16': 117,
          '44': 119,
          '45': 118,
          "isEdit": true,
        }
      ],
      allUser: [],
      form: {
        id: null,
        ratioNo: null,
        ratioName: null,
        primaryDesignatorId: null,
        primaryName: null,
        stirringTime: null,
        outletThickened:null,
        unilateralCapacity: null,
        waterBinderRatio: null,
        sandRatio: null,
        admixtureParameter: null,
        squareMeasure: null,
        temperature: null,        
        updateBy: null,
        updateTime: null,
        remark: null,
        status: null,
        informationDTOS: [],  
      },
      rules: {
        ratioName: [
          { required: true, message: "请填写配比名称", trigger: "change" },
        ],
        primaryDesignatorId: [
          { required: true, message: "请选择主标号", trigger: "change" },
        ],
        stirringTime: [
          { required: true, message: "请选搅拌时间", trigger: "change" },
        ],
        outletThickened: [
          { required: true, message: "请选择出机坍稠", trigger: "change" },
        ],
      },
      PrimaryNameList: [],
      tableColData:[], //原材料表头-原料码表信息tree数据
    };
  },
  created() {
    this.getPrimaryNameList();
    this.getMaterialCodeTreeList();
    this.userId = this.$route.query.id;
    console.log('this.userId', this.userId);
    
    // if (this.userId) {
    //   this.getUserInfo(this.userId);
    // }
  },
  mounted() {
    for (let index = 0; index < 16; index++) {
      this.originData.push(this.originData[0])
      
    }
  },
  computed: {
    title() {
      return !this.$route?.query?.id ? "新增标准配比" : "修改标准配比";
    },
    queryDateArr: {
      get() {
        if (this.queryParams?.startTime) {
          return [this.queryParams?.startTime, this.queryParams?.endTime];
        }
        return [];
      },
      set(value) {
        this.queryParams.startTime = value[0];
        this.queryParams.endTime = value[1];
      },
    },
  },
  methods: {
    /**
     * 获取主要名称列表
     * 该函数没有参数。
     */
    getPrimaryNameList() {
      // 使用listDesignator函数进行请求，分页参数为第1页，每页1000条
      listDesignator({ pageNum: 1, pageSize: 1000 }).then((res) => {
        this.PrimaryNameList = res?.rows;
        console.log('res',  this.PrimaryNameList); // 打印请求结果
      });
    },
    /**
     * 获取用料码表列表
     * 该函数没有参数。
     */
    getMaterialCodeTreeList() {
      getMaterialCodeList().then((res) => {
        this.tableColData = res?.data;
        console.log('res',  this.tableColData);
      });
    },      
    handleBack() {
      this.$router.push({
        path: "/qualityCenter/ratioManage/ratio",
      });
    },

    // 删除
    handelDelete(obj) {},
    // 运费
    handleSetFreight(obj) {
      this.$refs.setfreight.handelInit(obj);
    },
    handlePrimaryIdChange() {
      this.PrimaryNameList.forEach((item) => {
        if (item.id === this.form.primaryDesignatorId) {
          this.form.primaryName = item.name;
        }
      });
      console.log('this.form', this.form);
      
    },
    addNumberRules() {
      // 需要添加不可为负数的检验字段
      const numberRules = [
        "bgmd",
        "dldykzddj",
        "kzddjykzzj",
        "kdf",
        "mdf",
        "ksdj",
        "klsydj",
        "kllzstdj",
        "kllzstdjdtlf",
        "kthxndj",
        "zmsxndjyxn",
        "tsxs",
        "kzdj",
        "gmddj",
        "xsldj",
        "fhdj",
        "cd",
        "bsl",
        "kdxqdssl",
        "kdxzlssl",
        "njlsqd",
        "ssl",
        "ksdj",
      ];
      numberRules.forEach((item) => {
        this.rules[item] = [
          {
            validator: (rule, value, callback) => {
              console.log(rule);
              if (Object.is(Number(value), NaN)) {
                callback(new Error("请输入数字"));
              }
              if (+value < 0) {
                callback(new Error("不能为负数"));
              } else {
                callback();
              }
            },
            trigger: "blur",
          },
        ];
      });
    },
    handleSubmit() {
      this.$refs.form.validate((valid) => {
        if (valid) {
          if (this.id) {
            updateOrders({
              ...this.form,
            }).then((res) => {
              this.$message.success("更新成功");
              this.$router.push({ path: "/purchase/contract/index" });
            });
          } else {
            addOrders({
              ...this.form,
            }).then((res) => {
              this.$message.success("新增成功");
              this.$router.push({ path: "/purchase/contract/index" });
            });
          }
        } else {
          return false;
        }
      });
    },
    handlerClick(id, isDelete) {
      if (isDelete) {
        this.$confirm("确定要删除该原料吗？", "提示", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        })
          .then(() => {
            console.log('isDelete', isDelete);
            this.tableData[0][id] = "";
            // 具体逻辑
          })
          .catch(() => { });  
          return;      
      }
      // 打开add原材料弹窗
      this.$refs.customDialog.getList();
      this.dialogVisible = true;
    },
    closeHandler() {
      this.dialogVisible = false;      
    },
  },
};
</script>
<style lang="scss" scoped>
.origin_add_info {
  display: flex;
  justify-content: end;
  align-items: end;
  padding-bottom: 10px;
}
.container {
  height: 100%;
  ::v-deep.el-card__body {
    height: 100%;
    display: flex;
    flex-direction: column;
    overflow: hidden;
  }
  .content {
    flex: 1;
    overflow-x: hidden;
    overflow-y: auto;
  }
}
::v-deep .el-select {
  width: 100%;
}
</style>
